package com.example.movie.common.ws

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import com.alibaba.fastjson.JSON
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.constants.LoadingState
import com.example.movie.data.user.model.vo.QrOrderLoadingState
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

class WebSocketClient(private val handler: Handler) :
    WebSocketClient(URI.create(AppConstants.WS_URL)) {

    override fun onOpen(handshakedata: ServerHandshake?) {
        Log.d("", "onOpen: 已连接websocket")
    }

    override fun onMessage(message: String?) {
        Log.d("", "onMessage: 已接收到webSocket消息")
        val state = JSON.parseObject(message, QrOrderLoadingState::class.java)
        with(Message()) {
            what = LoadingState.OK
            val bundle = Bundle()
            bundle.putSerializable("state", state)
            data = bundle
            handler.sendMessage(this)
        }
    }

    override fun onClose(code: Int, reason: String?, remote: Boolean) {
        Log.e("", "onClose: 已关闭websocket code = $code reason = $reason remote = $remote")
    }

    override fun onError(ex: Exception?) {
        Log.d("", "onError: 出错websocket $ex")
    }


}